"""
file: util.py
Author: 城下秋草
Desc: 公共方法模块
"""
import json
import os.path

import yaml
from pom.util.custom_exception import FileTypeError
from pom.util.paths import config_dir


# def get_root():
#     return os.path.dirname(os.path.dirname(__file__))
#
# root_dir = get_root()
# data_dir = os.path.join(root_dir,"data")
# case_dir = os.path.join(root_dir,"cases")
# config_dir = os.path.join(root_dir,"config")
# log_dir = os.path.join(root_dir,"logs")

def get_json_data(jsonfile:str):
    if not os.path.exists(jsonfile):
        raise FileNotFoundError(f"{jsonfile}并不存在！")

    if not jsonfile.endswith(".json"):
        raise FileTypeError("json")

    with open(jsonfile,"r",encoding="utf-8") as file:
        return json.load(file)

def get_yml_data(ymlfile:str):
    if not os.path.exists(ymlfile):
        raise FileNotFoundError(f"{ymlfile}并不存在！")

    if not (ymlfile.endswith(".yml") or ymlfile.endswith(".yaml")):
        raise FileTypeError("yml or yaml")

    with open(ymlfile,"r",encoding="utf-8") as file:
        return yaml.safe_load(file)

class Config:
    def __init__(self):
        self.config = get_yml_data(os.path.join(config_dir,"config.yml"))

    def get_config(self, item:str):
        def recu_find(d:dict):
            for key,value in d.items():
                if key == item:
                    return value
                if isinstance(value,dict):
                    config = recu_find(value)
                    if config is not None:
                        return config

        return recu_find(self.config)